package iris_controller

import (
	"errors"
	"github.com/kataras/iris/v12"
	"gluenet/modules/manager/server/domain"
	"gluenet/modules/manager/server/infra"
	"gluenet/modules/manager/server/infra/prepare"
)

func init() {
	prepare.RegisterAuthController(func() {
		controller := NewIndexController()
		prepare.InjectAuthController(func() *Index {
			return controller
		})
	})
}

type Index struct {
	Index *domain.Index
}

func NewIndexController() *Index {
	r := &Index{}
	prepare.FetchDependency(&r.Index)
	return r
}

// Get serves
// Method:   GET
// Resource: http://localhost:8080/apis/index/add
func (r *Index) GetAdd(ctx iris.Context) *infra.Response {
	parms := ctx.URLParams()

	user_id := ctx.Values().GetString("user_id")

	if err := r.Index.Add(user_id, parms); err != nil {
		return infra.ResponseReqErr(err, nil)
	}

	return infra.ResponseOK(nil)
}

// Get serves
// Method:   GET
// Resource: http://localhost:8080/apis/index/get
func (r *Index) GetGet(ctx iris.Context) *infra.Response {

	user_id := ctx.Values().GetString("user_id")
	list, err := r.Index.Get(user_id)
	if err != nil && errors.Is(err, infra.DataNotFind) {
		return infra.ResponseReqErr(err, nil)
	}

	return infra.ResponseOK(list)
}

// Get serves
// Method:   GET
// Resource: http://localhost:8080/apis/index/reset
func (r *Index) GetReset(ctx iris.Context) *infra.Response {

	user_id := ctx.Values().GetString("user_id")
	if err := r.Index.ReSet(user_id); err != nil {
		return infra.ResponseReqErr(err, nil)
	}

	return infra.ResponseOK(nil)
}

// Get serves
// Method:   POST
// Resource: http://localhost:8080/apis/index/put
func (r *Index) PostPut(ctx iris.Context) *infra.Response {
	//parms := ctx.URLParams()

	user_id := ctx.Values().GetString("user_id")

	var req struct {
		List []interface{} `json:"list"`
	}
	ctx.ReadJSON(&req)

	if err := r.Index.Put(user_id, req.List); err != nil {
		return infra.ResponseReqErr(err, nil)
	}

	return infra.ResponseOK(nil)
}
